<template>
  <div class="form-config-container">
    <ElForm label-position="top">
      <ElFormItem label="标签对齐方式">
        <ElRadioGroup v-model="data.labelPosition">
          <ElRadioButton label="left">左对齐</ElRadioButton>
          <ElRadioButton label="right">右对齐</ElRadioButton>
          <ElRadioButton label="top">顶部对齐</ElRadioButton>
        </ElRadioGroup>
      </ElFormItem>

      <ElFormItem label="标签宽度">
        <ElInputNumber v-model.number="data.labelWidth" :min="0" />
      </ElFormItem>

      <ElFormItem label="组件尺寸">
        <ElRadioGroup v-model="data.size">
          <ElRadioButton label="large">大</ElRadioButton>
          <ElRadioButton label="default">默认</ElRadioButton>
          <ElRadioButton label="small">小</ElRadioButton>
        </ElRadioGroup>
      </ElFormItem>
      <ElFormItem
        label="列表属性"
        v-if="hasKey('pageType') || hasKey('listHeight') || hasKey('listExport')"
      >
        <ElCheckbox v-model="data.pageType" label="分页控制" @change="handleControl" />
        <!-- <ElCheckbox v-model="data.pageHide" label="隐藏分页栏" /> -->
        <ElCheckbox v-model="data.listHeight" label="自适应高度" />
        <ElCheckbox
          v-if="data.pageType"
          @change="handleExport"
          v-model="data.listExport"
          label="导出列表"
        />
        <ElCheckbox v-model="data.listUserCustomColumns" label="用户自定义列" />
        <ElCheckbox v-model="data.listBottomTurnPage" label="触底翻页" />
        <ElButton
          v-if="data.listExport"
          type="primary"
          style="margin-left: 30px"
          @click="handleField"
          >选择字段</ElButton
        >
      </ElFormItem>
      <ElFormItem label="导出文件名称" v-if="data.listExport">
        <ElInput v-model="data.exportFileName" placeholder="请输入导出文件名称" />
      </ElFormItem>
      <!-- <ElFormItem label="列表宽度强控" v-if="hasKey('listcontrol')">
        <ElSwitch
          inline-prompt
          active-text="控制"
          inactive-text="不控制"
          v-model="data.listcontrol"
        />
      </ElFormItem> -->
      <ElFormItem label="列表选择项" v-if="hasKey('listselection')">
        <ElRadioGroup v-model="data.listselection" @change="handleListSelectionChange">
          <ElRadioButton label="0">无</ElRadioButton>
          <ElRadioButton label="1">单选</ElRadioButton>
          <ElRadioButton label="2">当页多选</ElRadioButton>
          <ElRadioButton label="3">跨页多选</ElRadioButton>
        </ElRadioGroup>
      </ElFormItem>
      <ElFormItem label="列表主键字段" v-if="data.listselection === '3' && hasKey('listselection')">
        <ElInput v-model="data.listPrimaryField" />
      </ElFormItem>
      <ElFormItem label="默认排序字段" v-if="hasKey('listselection')">
        <ElInput v-model="data.defaultSortField" />
      </ElFormItem>
      <ElFormItem label="排序方式" v-if="hasKey('listselection')">
        <ElSelect v-model="data.sortBy">
          <ElOption value="asc" label="升序" />
          <ElOption value="desc" label="降序" />
        </ElSelect>
      </ElFormItem>
      <ElFormItem label="页面数量" v-if="hasKey('pagEnum')">
        <ElInputNumber v-model.number="data.pagEnum" :min="0" />
      </ElFormItem>
      <ElFormItem label="可选页面数量" v-if="hasKey('pageSizes')">
        <ElInput v-model="data.pageSizes" />
      </ElFormItem>
      <!-- <ElFormItem label="前固定列数" v-if="hasKey('locationon')">
        <ElInputNumber v-model.number="data.locationon" />
      </ElFormItem>
      <ElFormItem label="后固定列数" v-if="hasKey('locationback')">
        <ElInputNumber v-model.number="data.locationback" />
      </ElFormItem> -->
      <ElFormItem
        :label="data.listHeight ? '列表高度（calc函数自适应动态计算高度）' : '列表高度'"
        v-if="hasKey('pageh')"
      >
        <ElInput v-model.number="data.pageh" />
      </ElFormItem>
      <ElFormItem label="查询界面" v-if="hasKey('query')">
        <ElInput v-model="data.query" />
      </ElFormItem>
      <ElFormItem label="绑定事件" v-if="hasKey('actionNo')">
        <ElInput v-model="data.actionNo" />
      </ElFormItem>
      <ElFormItem
        label="流程默认显示模式"
        style="display: flex; flex-direction: column"
        v-if="hasKey('displayMode')"
      >
        <ElSelect v-model="data.displayMode" style="flex: 1">
          <ElOption
            v-for="item in displayModeForm"
            :key="item.value"
            :value="item.value"
            :label="item.label"
          />
        </ElSelect>
      </ElFormItem>
    </ElForm>
    <ElDialog
      :model-value="fieldPop"
      title="字段选择"
      :before-close="handleClose"
      :destroy-on-close="true"
    >
      <div class="table_content_tables">
        <div class="button">
          <ElButton type="primary" @click="handleFieldAdd">新增</ElButton>
          <ElButton type="danger" @click="handleFieldDelete">删除</ElButton>
        </div>
        <ElTable
          ref="TablesData"
          :data="data.fieldList"
          style="width: 100%"
          :max-height="450"
          border
          table-layout="fixed"
          @selection-change="handleSelectionChange"
        >
          <ElTableColumn type="selection" width="45" />
          <ElTableColumn label="序号">
            <template #default="scope">
              <ElInput v-model="scope.row.index" @input="handleSortInput" />
            </template>
          </ElTableColumn>
          <ElTableColumn prop="element_name" label="字段名">
            <template #default="scope">
              <ElInput v-model="scope.row.element_name" />
            </template>
          </ElTableColumn>
          <ElTableColumn prop="element_code" label="字段编号">
            <template #default="scope">
              <ElInput v-model="scope.row.element_code" />
            </template>
          </ElTableColumn>
          <ElTableColumn prop="element_isdefault" label="是否默认" width="100">
            <template #default="scope">
              <ElSwitch
                inline-prompt
                active-text="是"
                :active-value="1"
                inactive-text="否"
                :inactive-value="0"
                v-model="scope.row.element_isdefault"
              />
            </template>
          </ElTableColumn>
          <ElTableColumn label="操作">
            <template #default="scope">
              <ElButton type="text" @click="handleAscendingOrder(scope.$index)">升序</ElButton>
              <ElButton type="text" @click="handleDescendingOrder(scope.$index)">降序</ElButton>
            </template>
          </ElTableColumn>
        </ElTable>
      </div>
    </ElDialog>
  </div>
</template>

<script lang="ts">
  import { WidgetFormType, displayModeForm } from '@/types/element';
  import { PropType } from 'vue';
  import { debounce } from 'lodash-es';

  interface Fieldtype {
    element_code: string;
    element_name: string;
  }

  export default defineComponent({
    name: 'FormConfig',
    props: {
      config: {
        type: Object as PropType<WidgetFormType['config']>,
        required: true,
      },
      json: {
        type: Object,
      },
      pattern: {
        type: String,
        default: 'pc',
      },
    },
    emits: ['update:config'],
    setup(props, context) {
      const fieldPop = ref<boolean>(false);
      const data = ref(props.config);
      const MultiSelectDataFirst = ref<Fieldtype[]>([]);
      watch(data, () => context.emit('update:config', data));
      const hasKey = (key: string) => Object.keys(data.value).includes(key);
      const handleControl = (value: boolean) => {
        if (!value) {
          data.value.listExport = false;
          data.value.exportFileName = '';
        }
      };

      const handleExport = (value: boolean) => {
        if (value) {
          if (!data.value.fieldList.length) {
            data.value.fieldList = props.json?.display_area.filter(
              (item) =>
                !['buttonArea', 'unit', 'custom', 'button', 'uploadForm'].includes(
                  item.element_control,
                ),
            );
          }
          data.value.fieldList = data.value.fieldList.map(
            ({ element_name, element_code }, index) => ({
              element_name,
              element_code,
              element_isdefault: 1,
              index: index + 1,
            }),
          );
        } else {
          data.value.fieldList = [];
        }

        if (!value) {
          data.value.exportFileName = '';
        }
      };

      // 列表导出字段选择
      const handleField = () => {
        fieldPop.value = !fieldPop.value;
        data.value.fieldList.forEach((item, index) => {
          if (!item.index) {
            item.index = index + 1;
          }
        });
      };
      const handleClose = () => (fieldPop.value = !fieldPop.value);

      const handleSelectionChange = async (value: Fieldtype[]) => {
        MultiSelectDataFirst.value = value;
      };

      const handleFieldAdd = () => {
        data.value.fieldList.push({
          element_name: '',
          element_code: '',
          element_isdefault: 1,
          index: data.value.fieldList.length + 1,
        });
      };
      const handleFieldDelete = () => {
        if (!MultiSelectDataFirst.value.length) {
          ElMessage.warning('请选择数据！');
        } else {
          data.value.fieldList = data.value.fieldList.filter(
            (row) => !MultiSelectDataFirst.value.includes(row),
          );
          MultiSelectDataFirst.value = [];
          data.value.fieldList.forEach((item, index) => {
            item.index = index + 1;
          });
        }
      };
      const handleListSelectionChange = (value: string) => {
        if (value === '3') {
          data.value.listPrimaryField = '';
        } else {
          delete data.value.listPrimaryField;
        }
      };
      const handleSortInput = debounce(() => {
        const userAgent = navigator.userAgent;

        // 判断是否为WebKit内核（Chrome、Safari等）
        if (
          /WebKit/i.test(userAgent) ||
          /Blink\//i.test(userAgent) ||
          /Trident\//i.test(userAgent)
        ) {
          data.value.fieldList.sort((a, b) => a.index - b.index - 1);
        }

        // 判断是否为Gecko内核（Firefox）
        if (/Gecko\//i.test(userAgent) || /Presto\//i.test(userAgent)) {
          data.value.fieldList.sort((a, b) => {
            const result = a.index - b.index;
            return result !== 0 ? result : a.index === b.index ? -1 : 1;
          });
        }

        // 更新索引
        data.value.fieldList.forEach((item, index) => {
          item.index = index + 1;
        });
      }, 1000);

      const handleAscendingOrder = (index: number) => {
        if (index > 0) {
          const removedItem = data.value.fieldList.splice(index, 1)[0];
          data.value.fieldList.splice(index - 1, 0, removedItem);
          // 更新索引
          data.value.fieldList.forEach((item, index) => {
            item.index = index + 1;
          });
        }
      };
      const handleDescendingOrder = (index: number) => {
        if (index < data.value.fieldList.length - 1) {
          const removedItem = data.value.fieldList.splice(index, 1)[0];
          data.value.fieldList.splice(index + 1, 0, removedItem);
          // 更新索引
          data.value.fieldList.forEach((item, index) => {
            item.index = index + 1;
          });
        }
      };
      return {
        fieldPop,
        data,
        displayModeForm,
        hasKey,
        handleControl,
        handleExport,
        handleField,
        handleClose,
        handleSelectionChange,
        handleFieldAdd,
        handleFieldDelete,
        handleListSelectionChange,
        handleSortInput,
        handleAscendingOrder,
        handleDescendingOrder,
      };
    },
  });
</script>

<style lang="scss" scoped>
  .table_content_tables {
    .button {
      margin-bottom: 10px;
    }
    :deep(th) {
      color: #000;
      background-color: rgba(9, 96, 189, 0.05);
      background-image: linear-gradient(rgba(9, 96, 189, 0.1), #fff);
    }
    :deep(.el-radio) {
      margin-right: 15px;
    }
    :deep(.el-radio:last-child) {
      margin-right: 0;
    }
    :deep(.el-radio--large) {
      height: 25px;
    }
  }
  :deep(.el-dialog__body) {
    padding: 15px 20px 20px 20px;
  }
  :deep(.el-radio-button__inner) {
    padding: 8px 13px;
  }
</style>
